var express = require('express');
var router = express.Router();
const { query } = require('../db');
const app = express()
//通过json这个中间件解析json格式的数据
app.use(express.json())
//通过使用urlencoded解码数据
app.use(express.urlencoded({ extended: false }))
//获取列表
router.post('/list', async function (req, res, next) {
    // 获取分页参数
    var key = req.body.key || '';
    var pageNum = Number(req.body.pageNum);
    var pageSize = Number(req.body.pageSize);
    var start = (pageNum - 1) * pageSize;
    //  
    var sql = `select * from hotel_room   ORDER BY id desc   limit ${start},${pageSize} `;
    // 查询数据库
    var result = await query(sql).catch(next)
    var sql_all = 'select * from  hotel_room ';
    var result_all = await query(sql_all).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            data: result,
            total: result_all.length
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// var date = new Date('2022-10-23 15:15:38');
// var time1 = date.getTime();
// console.log(date,time1)

async function f1() {
    var sql = `select * from income`;
    var result = await query(sql).catch();
    // console.log(result)
    var list = result;
    var data = result[0] || [];
    
        for (var i = 0; i < list.length; i++) {
            list[i].dates = new Date(list[i].date_s).getTime();
            // console.log(list[i].dates);

            list[i].month = new Date(list[i].date_s).getMonth() + 1
            list[i].days = new Date(list[i].date_s).getDate();
            list[i].times = list[i].month + '-' + list[i].days
 }




//    console.log(data.length,"data")



}

// f1()

// let arr1 = [
//     {
//         id: 18,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-23'
//       } ,
//       {
//         id: 18,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-23'
//       } ,
//       {
//         id: 18,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-23'
//       } ,
//       {
//         id: 18,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-23'
//       }  ,

//       {
//         id: 19,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-24'
//       }   ,

//       {
//         id: 19,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-24'
//       }   ,
//       {
//         id: 19,
//         room_id: '20',
//         roomnum: '1004',
//         date_s: '2022-10-23 15:33:48',
//         income: 123,
//         account: '333',
//         state: '1',
//         dates: 1666510428000,
//         month: 10,
//         days: 23,
//         times: '10-24'
//       }   
// ]  
// // 数据合并    array:需合并的数据
// function arrMerge(array) {
    
//     // 保存新数组
//     let newArr = [];
//     array.forEach(item => {
//         // 保存判断结果
//         let res = newArr.isExist(item.times, "times");
//         // 若不存在新数组中，则直接追加进新数组
//         if (res == -1) {
//             newArr.push(item);
//         } else {
//             newArr[res]['income']+=item['income']
            
//         };
//     });
//     return newArr;
// };

// // 判断元素是否存在数组中对象属性中  value:元素   key:对象属性   
// Array.prototype.isExist = function (value, key) {
//     for (let i = 0, len = this.length; i < len; i++) {
//         // 若存在，则返回对应的索引
//         if (this[i][key] === value) {
//             return i;
//         }
//     }
//     // 否则返回 -1
//     return -1;
// }
// arrMerge(arr1)

// console.log(arrMerge(arr1));



// 房间收益统计
router.post('/tongji', async function (req, res, next) {

    var sql = `select * from income`;
    var result = await query(sql).catch();
    // console.log(result)
    var list = result;
    var data = result[0] || [];
    
        for (var i = 0; i < list.length; i++) {
            list[i].dates = new Date(list[i].date_s).getTime();
            // console.log(list[i].dates);

            list[i].month = new Date(list[i].date_s).getMonth() + 1
            list[i].days = new Date(list[i].date_s).getDate();
            list[i].times = list[i].month + '-' + list[i].days
 }

// 数据合并    array:需合并的数据
function arrMerge(array) {
    
    // 保存新数组
    let newArr = [];
    array.forEach(item => {
        // 保存判断结果
        let res = newArr.isExist(item.times, "times");
        // 若不存在新数组中，则直接追加进新数组
        if (res == -1) {
            newArr.push(item);
        } else {
            newArr[res]['income']+=item['income']
            
        };
    });
    return newArr;
};

// 判断元素是否存在数组中对象属性中  value:元素   key:对象属性   
Array.prototype.isExist = function (value, key) {
    for (let i = 0, len = this.length; i < len; i++) {
        // 若存在，则返回对应的索引
        if (this[i][key] === value) {
            return i;
        }
    }
    // 否则返回 -1
    return -1;
}
var list_retrun=arrMerge(list).slice(0,7)

var day_list=[];
var income_list=[];
for(var i=0;i<list_retrun.length;i++){
    day_list.push(list_retrun[i].times);
    income_list.push(list_retrun[i].income)

}
    // 返回数据
    if (result) {
        res.json({
            code: 200,
          data:{
            day_list:day_list,
            income_list:income_list
          }
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})


// 故障上报
router.post('/addROOMreport', async function (req, res, next) {
    console.log(req.body)
    // 获取参数 房间号 状态 房间价格
    // var id = req.body.id;
    var roomnum = req.body.roomnum;
    var user_accout = req.body.user_accout;
    var room_id = req.body.room_id;
    var baoxiuname = req.body.baoxiuname;

    // 修改房间表为 3状态
    var sql = `UPDATE hotel_room SET ${baoxiuname}='3'  WHERE id=${room_id}`;
    console.log(sql, "sql")
    var result = await query(sql).catch(next);
    // console.log(result,"result")

    // 向保修表插入数据
    var report_sql = `INSERT INTO report(roomnum,user_accout,room_id,baoxiuname) VALUES('${roomnum}','${user_accout}','${room_id}','${baoxiuname}')`;
    var repoet_res = await query(report_sql).catch(next);
    // console.log(repoet_res,"repoet_res");
    // console.log( report_sql," report_sql");

    // 返回数据
    if (repoet_res) {
        res.json({
            code: 200,
            msg: "上报成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 获取故障上报
router.post('/ROOMreportList', async function (req, res, next) {
    // 获取分页参数
    var key = req.body.key || '';
    var pageNum = Number(req.body.pageNum);
    var pageSize = Number(req.body.pageSize);
    var start = (pageNum - 1) * pageSize;
    //  
    var sql = `select * from report   ORDER BY id desc   limit ${start},${pageSize} `;
    // 查询数据库
    var result = await query(sql).catch(next)
    var sql_all = 'select * from  report ';
    var result_all = await query(sql_all).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            data: result,
            total: result_all.length
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 修复故障
router.post('/ROOMrepair', async function (req, res, next) {
    console.log(req.body, 'req.body')
    // 获取参数 房间号 状态 房间价格
    var id = Number(req.body.id);
    var room_id = Number(req.body.room_id);
    var baoxiuname = req.body.baoxiuname;

    // 删除记录
    var del_sql = `delete from report where id=${id} `;
    var del_res = await query(del_sql).catch(next);
    console.log(del_sql, 'del_sql')
    var sql = `update hotel_room SET ${baoxiuname}=0 where id=${room_id}`;
    console.log(sql, 'sql')
    var result = await query(sql).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "修复成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})



// 修改房间状态
router.post('/editSTATE', async function (req, res, next) {
    console.log(req.body)
    // 获取参数 房间号 状态 房间价格
    var id = req.body.id;

    var ketingdeng = req.body.ketingdeng;
    var dianshi = req.body.dianshi;
    var chuangtoudeng = req.body.chuangtoudeng;
    var xiyujiandeng = req.body.xiyujiandeng;
    var zoulangdeng = req.body.zoulangdeng;
    var kongtiao = req.body.kongtiao;
    var bingxiang = req.body.bingxiang;




    var sql = `UPDATE hotel_room SET ketingdeng='${ketingdeng}',dianshi='${dianshi}',chuangtoudeng='${chuangtoudeng}',
    xiyujiandeng='${xiyujiandeng}',zoulangdeng='${zoulangdeng}',kongtiao='${kongtiao}',bingxiang='${bingxiang}'
    WHERE id=${id}`;
    //     // var sql= `UPDATE hotel_room SET roomstate='${roomstate}'  WHERE id=${id}`;
    //     var slq_yuyue = ` delete  from subscriberoom WHERE room_id='${id}'`;

    // if(roomstate==2){
    //      var slq_yuyue = `INSERT INTO subscriberoom (room_id,roomnum,user_accout,user_name,room_price,roomstate) VALUES ('${id}','${roomnum}','${user_accout}','${user_name}','${room_price}','0');`;
    //     var result_slq_yuyue = await query(slq_yuyue).catch(next);
    //     console.log(slq_yuyue,"result_slq_yuyue")
    // }

    // var result_slq_yuyue = await query(slq_yuyue).catch(next);
    var result = await query(sql).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "修改成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 获取房间指定
router.post('/room_detail', async function (req, res, next) {
    var id = Number(req.body.room_id);
    var sql = `select * from hotel_room  where id=${id} `;
    // 查询数据库
    var result = await query(sql).catch(next)

    // 返回数据
    if (result) {
        res.json({
            code: 200,
            data: result,
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }

})

// 添加
router.post('/add', async function (req, res, next) {
    // 获取参数 房间号 状态 房间价格
    var roomnum = req.body.roomnum;
    var roomstate = 0;
    var room_price = req.body.room_price;
    var room_type = req.body.room_type;
    var room_img = req.body.room_img;

    var sql = `INSERT INTO hotel_room (roomnum,roomstate,room_price,room_img,room_type) VALUES ('${roomnum}','${roomstate}','${room_price}','${room_img}','${room_type}')`;
    var result = await query(sql).catch(next);

    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "添加成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 获取房间类型
router.post('/rommTypeList', async function (req, res, next) {
    // 
    var sql = `select * from room_type`;
    // 查询数据库
    var result = await query(sql).catch(next)
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            data: result,

        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})


router.post('/editROOM_INFO', async function (req, res, next) {
    console.log(req.body)
    // 获取参数 房间号 状态 房间价格
    var id = req.body.id;
    var room_img = req.body.room_img;
    var room_type = req.body.room_type;
    var room_price = req.body.room_price;
    var sql = `UPDATE hotel_room SET room_img='${room_img}',room_type='${room_type}',room_price='${room_price}'  WHERE id=${id}`;
    // var sql= `UPDATE hotel_room SET roomstate='${roomstate}'  WHERE id=${id}`;

    var result = await query(sql).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "修改成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})



// 修改房间状态
router.post('/edit', async function (req, res, next) {
    console.log(req.body)
    // 获取参数 房间号 状态 房间价格
    var id = req.body.id;
    var roomstate = req.body.roomstate;
    var roomnum = req.body.roomnum;
    var user_accout = req.body.user_accout;
    var user_name = req.body.user_name;
    var room_price = Number(req.body.room_price);
    var status_ = req.body.status_;
    var sql = `UPDATE hotel_room SET roomstate='${roomstate}',user_accout='',user_name=''  WHERE id=${id}`;
    // var sql= `UPDATE hotel_room SET roomstate='${roomstate}'  WHERE id=${id}`;


    if (status_ == "quxiao") {
        // 退还支付金额

        var slq_tuifei = `update user set balance=balance+${room_price} where account='${user_accout}'`;
        var tuifei_res = await query(slq_tuifei).catch(next);

        var del_sql_income = `delete from income where account='${user_accout}'`;
        var del_res = await query(del_sql_income).catch(next);

    }
    if (status_ == "ruzhu") {
        var sql_income = `update  income set state=1 where account='${user_accout}'`;
        console.log(sql_income)
        var income_res = await query(sql_income).catch(next);
    }

    if (roomstate == 2) {
        var slq_roomstate_2 = `INSERT INTO subscriberoom (room_id,roomnum,user_accout,user_name,room_price,roomstate) VALUES ('${id}','${roomnum}','${user_accout}','${user_name}','${room_price}','0');`;
        var result_roomstate_2 = await query(slq_roomstate_2).catch(next);
        console.log(result_roomstate_2,"result_roomstate_2")

    }
    if (status_ == "tuifang") {
        var slq_yuyue = ` delete  from subscriberoom WHERE room_id='${id}'`;
        var result_slq_yuyue = await query(slq_yuyue).catch(next);
        console.log("来删除了")
    }


    var result = await query(sql).catch(next);
    console.log(result, "result=--")
    // 返回数据
    if (result) {
        console.log("返回")
        res.json({
            code: 200,
            msg: "修改成功!"
        })
        return false

    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }


})



// 删除
router.post('/del', async function (req, res, next) {
    // 获取参数
    var id = Number(req.body.id);
    var sql = `delete from fangjian where id=${id} `
    // 查询数据库
    var result = await query(sql).catch(next)
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})
// 用户添加预约房间
router.post('/userSubscribeRoom', async function (req, res, next) {
    // 获取参数 房间号 状态 房间价格
    var roomnum = req.body.roomnum;
    var id = Number(req.body.id);


    var user_accout = req.body.user_accout;
    var user_name = req.body.user_name;
    var roomstate = req.body.roomstate;

    // 只可以预约一间房
    var check_sql = `select * from hotel_room where user_accout='${user_accout}' `;
    var check_result = await query(check_sql).catch(next);
    if (check_result.length >= 1) {
        res.json({
            code: -9999,
            msg: "只可以预约一间房"
        })
        return false
    }

    // 先将房间改为已经入住 
    var hotel_room_sql = `UPDATE hotel_room SET roomstate=1,user_accout='${user_accout}',user_name='${user_name}'  WHERE id=${id}`;
    var hotel_room_result = await query(hotel_room_sql).catch(next);
    // 添加到预约房间列表
    // var slq_yuyue = `INSERT INTO subscriberoom (room_id,roomnum,user_accout,user_name,room_price,roomstate) VALUES ('${id}','${roomnum}','${user_accout}','${user_name}','${room_price}','0');`;
    // var result_slq_yuyue = await query(slq_yuyue).catch(next);
    // console.log(slq_yuyue,"result_slq_yuyue")
    // 返回数据
    if (hotel_room_result) {
        res.json({
            code: 200,
            msg: "添加成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})



// 同意
router.post('/sureRoom', async function (req, res, next) {
    // 获取参数 房间号 状态 房间价格
    var roomnum = req.body.roomnum;
    var id = Number(req.body.id);
    var room_price = req.body.room_price;
    var user_accout = req.body.user_accout;
    var user_name = req.body.user_name;
    var roomstate = req.body.roomstate;
    // 先将房间改为已经入住 
    var hotel_room_sql = `UPDATE hotel_room SET roomstate=2,user_accout='${user_accout}',user_name='${user_name}'  WHERE id=${id}`;
    var hotel_room_result = await query(hotel_room_sql).catch(next);
    // 添加到房间列表
    var slq_yuyue = `INSERT INTO subscriberoom (room_id,roomnum,user_accout,user_name,room_price,roomstate) VALUES ('${id}','${roomnum}','${user_accout}','${user_name}','${room_price}','0');`;
    var result_slq_yuyue = await query(slq_yuyue).catch(next);
    console.log(slq_yuyue, "result_slq_yuyue")
    // 返回数据
    if (result_slq_yuyue) {
        res.json({
            code: 200,
            msg: "添加成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})



// 用户退房
router.post('/user_tuifang', async function (req, res, next) {
    // 获取参数 房间号 状态 房间价格

    var id = Number(req.body.id);
    var room_id = req.body.room_id;
    var user_accout = req.body.user_accout;
    var user_name = req.body.user_name;

    // 先将房间改为退房 
    var hotel_room_sql = `UPDATE hotel_room SET roomstate=0,user_accout='',user_name=''  WHERE id=${room_id}`;
    console.log(hotel_room_sql, "hotel_room_sql=")
    var hotel_room_result = await query(hotel_room_sql).catch(next);
    // delete  from user  where id ='2020'
    // 预约房间改成退房
    var slq_yuyue = ` delete  from subscriberoom WHERE id=${id}`;
    var result_slq_yuyue = await query(slq_yuyue).catch(next);
    console.log(result_slq_yuyue, "result_slq_yuyue")
    // 返回数据
    if (result_slq_yuyue) {
        res.json({
            code: 200,
            msg: "成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 获取房间列表
router.post('/subscribeList', async function (req, res, next) {
    // 获取分页参数
    var key = req.body.key || '';
    var pageNum = Number(req.body.pageNum);
    var pageSize = Number(req.body.pageSize);
    var start = (pageNum - 1) * pageSize;
    var user_accout = req.body.user_accout;
    //  
    var sql = `select * from subscriberoom where user_accout='${user_accout}'  ORDER BY id desc   limit ${start},${pageSize} `;
    // 查询数据库
    var result = await query(sql).catch(next)
    var sql_all = 'select * from  subscriberoom';
    var result_all = await query(sql_all).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            data: result,
            total: result_all.length
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 删除用户预约房间
router.post('/subscribeDel', async function (req, res, next) {
    // 获取参数
    var id = Number(req.body.id);
    var sql = `delete from subscriberoom where id=${id}`
    // 查询数据库
    var result = await query(sql).catch(next)
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})



module.exports = router;

